package com.vimhe.easyimport.util;

import com.vimhe.easyimport.exception.ImportException;

/**
 * 进制转换工具类
 * <p>主要用于把Excel中的列转换为对应的数字</p>
 *
 * @author Vimhe
 */
public final class HexUtils {

    private HexUtils() {
    }

    /**
     * 把字母转换成数字
     * <p>“A” => “1”</p>
     * <p>“C” => “3”</p>
     * <p>“AA” => “27”</p>
     * <p>相当于把26进制转换为10进制</p>
     *
     * @param name 列名称
     * @return 索引
     */
    public static int letter2Number(String name) {
        name = name.toUpperCase();
        char[] chars = name.toCharArray();
        int n = 0;
        for (int i = chars.length - 1, j = 1; i >= 0; i--, j *= 26) {
            char c = chars[i];
            if (c < 'A' || c > 'Z') {
                throw new ImportException("无法解析的列信息：" + c);
            }
            n += (c - 64) * j;
        }

        return n;
    }

    /**
     * 把数字转换成字母
     * <p>“1” => “A”</p>
     * <p>“3” => “C”</p>
     * <p>“27” => “ZZ”</p>
     * <p>相当于把10进制转换为26进制</p>
     *
     * @param index 索引
     * @return 列名称
     */
    public static String number2Letter(int index) {
        StringBuilder name = new StringBuilder();
        while (index > 0) {
            int m = index % 26;
            if (m == 0) {
                m = 26;
            }
            name.insert(0, (char) (m + 64));
            index = (index - m) / 26;
        }

        return name.toString();
    }

}
